package cn.scw.common.utils;

import cn.scw.common.exception.CustomException;
import cn.scw.common.utils.file.FileUploadUtils;
import com.baidu.aip.bodyanalysis.AipBodyAnalysis;
import org.json.JSONObject;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Base64;
import java.util.HashMap;
import java.util.UUID;

public class BaiduImgUtils {
    //设置APPID/AK/SK
//    public static final String APP_ID = "20474919";
//    public static final String API_KEY = "7ZrBraPDNT1qU7O6KihLxsSt";
//    public static final String SECRET_KEY = "puOUtCkL1RCXYCl2VlN391PYTBpwGepT";
    public static final String APP_ID = "24519736";
    public static final String API_KEY = "sGcLjc1XOX6fu7Zi83mlLGlm";
    public static final String SECRET_KEY = "SChGtSQQEeWlW08cpFvW4dwdZhb3cSHR";
    public static AipBodyAnalysis client;

    static {
        client = new AipBodyAnalysis(APP_ID, API_KEY, SECRET_KEY);
        client.setConnectionTimeoutInMillis(2000);
        client.setSocketTimeoutInMillis(60000);
    }

    public static void main(String[] args) {
//        String path="http://192.168.2.118:8181/profile/upload/2020/06/08/124d06db44807f79e5b3973d1d0e0d4b.jpg";
//        String newPath="D:/home/scw_print/uploadPath/"+path.substring(path.indexOf("upload"));
//        System.out.println(newPath);
////        imgSet("http://192.168.2.118:8181/profile/upload/2020/06/08/124d06db44807f79e5b3973d1d0e0d4b.jpg",255,255,0);
////        "D:/home/scw_print/uploadPath/upload/2020/06/08/124d06db44807f79e5b3973d1d0e0d4b.jpg"
//        imgSet(newPath,255,255,0);
 //       String path = "http://47.114.120.199/profile/upload/2020/06/21/2e9f8bab8722b50077879ec03cd5f391.png";
        String path = "C:\\Users\\C00145\\Pictures\\Camera Roll\\微信图片_20210709092859.png";
        imgSet(path,255,255,0);
        int index = path.lastIndexOf("/");

        String suffix = path.substring(path.lastIndexOf("."));
        String newPath = path.substring(0, index) + "/" + FileUploadUtils.encodingFilename(UUID.randomUUID().toString()) + suffix;
        System.out.println(path);
        System.out.println(newPath);

    }

    public static String imgSet(String path, int r, int g, int b) {
        bodySeg(path);
        Color color1 = new Color(r, g, b);

        int index = path.lastIndexOf("/");

        String suffix = path.substring(path.lastIndexOf("."));
        String newPath = path.substring(0, index) + "/" + FileUploadUtils.encodingFilename(UUID.randomUUID().toString()) + suffix;

        changePNGBackgroudColor(path, newPath, color1);
        return newPath;
    }


    /**
     * 人像分割，获取人像
     *
     * @param path
     * @return
     */
    private static String bodySeg(String path) {
        // 传入可选参数调用接口
        HashMap<String, String> options = new HashMap<String, String>();
        options.put("type", "foreground");

        // 参数为本地路径
        JSONObject res = client.bodySeg(path, options);
        System.out.println("========================================");
        System.out.println(res.toString());
        System.out.println("========================================");
        String foreground = res.getString("foreground");
        boolean image = GenerateImage(foreground, path);
        if (!image)
            throw new CustomException("图片处理错误");
        return path;
    }

    /**
     * 讲图片解码为文件
     *
     * @param imgStr
     * @param imgFilePath
     * @return
     */
    private static boolean GenerateImage(String imgStr, String imgFilePath) { // 对字节数组字符串进行Base64解码并生成图片
        if (imgStr == null) // 图像数据为空
            return false;
        Base64.Decoder decoder = Base64.getDecoder();
        try {
            // Base64解码
            byte[] b = decoder.decode(imgStr);
            for (int i = 0; i < b.length; ++i) {
                if (b[i] < 0) { // 调整异常数据
                    b[i] += 256;
                }
            }
            // 生成jpeg图片
            OutputStream out = new FileOutputStream(imgFilePath); // 新生成的图片
            out.write(b);
            out.flush();
            out.close();
            return true;
        } catch (Exception e) {
            System.out.println("出错了" + e.getMessage());
            return false;
        }
    }

    /**
     * 更换底色
     */
    private static void changePNGBackgroudColor(String sourceImage, String targetImage, Color backgroudColor) {
        try {
            BufferedImage result = changePNGBackgroudColor(sourceImage, backgroudColor);
            File output = new File(targetImage);

            ImageIO.write(result, "jpg", output);
        } catch (IOException e) {
            System.out.println("有问题了" + e.getMessage());
        }
    }


    /**
     * 更换底色
     */
    private static BufferedImage changePNGBackgroudColor(String sourceImage, Color backgroudColor) {
        try {
            File input = new File(sourceImage);
            BufferedImage image = ImageIO.read(input);

            BufferedImage result = new BufferedImage(
                    image.getWidth(),
                    image.getHeight(),
                    BufferedImage.TYPE_INT_RGB);

            Graphics2D graphic = result.createGraphics();
            graphic.drawImage(image, 0, 0, backgroudColor, null);
            graphic.dispose();
            return result;
        } catch (IOException e) {
            System.out.println("有问题了" + e.getMessage());
            return null;
        }
    }


}
